import requests
import json

# 发送请求
r1 = requests.get('https://api.github.com/events')
r2 = requests.post('http://httpbin.org/post', data={'key': 'value'})

# 传递URL参数
# payload = {'key1': 'value1', 'key2': 'value2'}
payload = {'key1': 'value1', 'key2': ['value2', 'value3']}
r3 = requests.get("http://httpbin.org/get", params=payload)
print(r3.url)

# 响应内容
print(r1.text)  # 文本内容
print(r1.encoding)
print(r1.content)  # 二进制内容
print(r1.json())  # JSON响应内容

r4 = requests.get('https://api.github.com/events', stream=True)
print(r4.raw.read())  # 原始内容

# 定制请求头
url = 'https://api.github.com/some/endpoint'
headers = {'user-agent': 'my-app/0.0.1'}
r5 = requests.get(url, headers=headers)

# post请求
payload = {'key1': 'value1', 'key2': 'value2'}
r6 = requests.post("http://httpbin.org/post", data=payload)
print(r6.text)
# 元祖参数
payload = (('key1', 'value1'), ('key1', 'value2'))
r7 = requests.post('http://httpbin.org/post', data=payload)
print(r7.text)

# json参数
url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
r = requests.post(url, data=json.dumps(payload))
# POST一个多部分编码(Multipart-Encoded)的文件

url = 'http://httpbin.org/post'
files = {'file': open('filepath/aaa.txt', 'rb')}
r8 = requests.post(url, files=files)
print(r8.text)

# 响应状态码
r9 = requests.get('http://httpbin.org/get')
print(r9.status_code)
